package com.biqee.service.user.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

import com.biqee.model.db.BqVersion;
import com.biqee.model.db.UserVersion;
import com.biqee.service.db.BqVersionService;
import com.biqee.service.user.UserPermissionService;

public class UserPermissionServiceImpl implements UserPermissionService {
	private static List<BqVersion> systemVersionList = new CopyOnWriteArrayList<BqVersion>();
	
	public void init() {
		loadAllVersionInfo();
	}

	private void loadAllVersionInfo() {
		List<BqVersion> versions = bqVersionService.readAll();
		if(versions == null) {
			versions = new ArrayList<BqVersion>();
		}
		
		UserPermissionServiceImpl.systemVersionList = new CopyOnWriteArrayList<BqVersion>(versions);
	}

	@Override
	public void reLoadAllVersionInfo() {
		loadAllVersionInfo();
	}
	
	@Override
	public boolean checkPermission(List<UserVersion> userVersions, String currentPermissionCode) {
		if (userVersions == null || currentPermissionCode == null) {
			return false;
		}

		Map<Long, Long> versionIds = new HashMap<Long, Long>();
		for(UserVersion userVersion : userVersions) {
			if(!isOutOfDate(userVersion)) {
				versionIds.put(userVersion.getVersionId(), userVersion.getVersionId());	
			}
		}
		
		for(BqVersion bqVersion : UserPermissionServiceImpl.systemVersionList) {
			if(versionIds.get(bqVersion.getId()) != null) {
				String permissionCodesStr = bqVersion.getPermissionCodes();
				String[] permissionCodes = permissionCodesStr.split(",");
				for(String permission : permissionCodes) {
					if(currentPermissionCode.equals(permission)) {
						return true;
					}
				}
			}
		}
		
		return false;
	}

	private boolean isOutOfDate(UserVersion userVersion) {
		Date gmtStart = userVersion.getGmtStart();
		Date gmtEnd = userVersion.getGmtEnd();
		Date now = new Date();
		if(now.before(gmtStart)) {
			return true;
		}
		
		if(now.after(gmtEnd)) {
			return true;
		}
		
		return false;
	}
	
	private BqVersionService bqVersionService;

	public void setBqVersionService(BqVersionService bqVersionService) {
		this.bqVersionService = bqVersionService;
	}
	
}
